package com.zking.seckillpro.exception;

import com.zking.seckillpro.util.JsonResponseBody;
import com.zking.seckillpro.util.JsonResponseStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.validation.valueextraction.ExtractedValue;

/**
 * SpringMvc全局异常处理
 */
@RestControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResponseBody<?> exceptionHandler(Exception e){
        e.printStackTrace();
    JsonResponseBody<?> jsonResponseBody=null;
    //判断异常是否为自定义的业务异常
        if(e instanceof BusinessException){
            BusinessException ex= (BusinessException) e;
            jsonResponseBody=new JsonResponseBody<>(ex.getJsonResponseStatus());
        }else if(e instanceof BindException){
            BindException ex= (BindException) e;
        //获取注解上定义的message消息
            String msg = ex.getFieldError().getDefaultMessage();
            jsonResponseBody=new JsonResponseBody<>();
            jsonResponseBody.setMsg(msg);
            jsonResponseBody.setCode(100999);
        }else{
            jsonResponseBody=new JsonResponseBody<>(JsonResponseStatus.ERROR);
        }
    return jsonResponseBody;
    }
}
